package com.cpo.dao;

import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.cpo.domain.CreditCard;
import com.cpo.domain.Person;
import com.cpo.interfaces.IPersonDao;

@Repository
@Transactional
public class PersonDao implements IPersonDao {

	public static Logger logger = Logger.getLogger("service");
	
	@Autowired
	private SessionFactory sessionFactory;
	
	public List<Person> getAll() {
		
		logger.debug("Retriving all persons");
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("FROM Person");
		return query.list();
	}

	
	public void delete(Integer id) {
		logger.debug("Deleting existing person");
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("FROM Person as p LEFT JOIN FETCH p.creditCards WHERE p.id="+id);
		Person person = (Person) query.uniqueResult();
		Set<CreditCard> creditCards = person.getCreditCards();
		session.delete(person);
		for(CreditCard creditcard:creditCards){
			session.delete(creditcard);
		}
	}

	
	public void edit(Person person) {
		logger.debug("Editing existing person");
		Session session = sessionFactory.getCurrentSession();
		Person existingPerson = (Person) session.get(Person.class, person.getId());
		
		existingPerson.setFirstName(person.getFirstName());
		existingPerson.setLastName(person.getLastName());
		existingPerson.setMoney(person.getMoney());
		existingPerson.setCreditCards(person.getCreditCards());
		session.save(existingPerson);
	}

	
	public Person get(Integer id) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("FROM Person as p LEFT JOIN FETCH p.creditCards WHERE p.id="+id);
		return (Person) query.uniqueResult();
	}

	
	public void add(Person person) {
		logger.debug("Adding new person");
		Session session = sessionFactory.getCurrentSession();
		session.save(person);
		
	}



}
